package com.h2cloud.ReactorTest.reactor.client;

/**
 * @Package: com.h2cloud.ReactorTest.reactor.client
 * @ClassName: NioSocketClient
 * @Author: wulongkai
 * @CreateTime: 2024/7/23 16:15
 * @Description:
 */

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

public class Client implements Runnable {

    String serverAddress;

    int port;

    public Client(String serverAddress, int port) {
        this.serverAddress = serverAddress;
        this.port = port;
    }

    @Override
    public void run() {
        try {
            InetSocketAddress hostAddress = new InetSocketAddress(serverAddress, port);
            SocketChannel client = SocketChannel.open(hostAddress);
            System.out.println("Client connected to server at " + hostAddress);

            // 发送消息到服务器
            String message = "Hello, Server!" + Thread.currentThread().getId();
            ByteBuffer buffer = ByteBuffer.wrap(message.getBytes(StandardCharsets.UTF_8));
            client.write(buffer);
            System.out.println(String.format("客户端 %s 发送数据完毕", Thread.currentThread().getId()));

            // 清空缓冲区以准备接收响应
            buffer.clear();

            // 接收服务器的响应
            int bytesRead = client.read(buffer);
            if (bytesRead > 0) {
                buffer.flip();
                byte[] bytes = new byte[buffer.remaining()];
                buffer.get(bytes);
                String response = new String(bytes, StandardCharsets.UTF_8);
                System.out.println("Server response: " + response);
            }

            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

